import { Form, Input, Modal } from "antd";
import { useEffect } from "react";
import { apiAddNovelTag, apiModifyNovelTag } from "~/api/novel";
import type { INovelTag } from "~/types/manage/content/config";

interface Props {
  visible: boolean;
  record?: INovelTag | null;
  onCancel?: () => void;
  onOk?: () => void;
}

export default function NovelTagModal(props: Props) {
  const [form] = Form.useForm<Partial<INovelTag>>();

  const _handler = {
    onCancel: () => {
      props.onCancel?.();
    },
    onOk: async () => {
      const value: INovelTag = form.getFieldsValue(true);
      if (value.id) {
        await apiModifyNovelTag(value.id, value);
      } else {
        await apiAddNovelTag(value);
      }
      props.onOk?.();
    },
  };

  useEffect(() => {
    if (!props.visible) {
      return;
    }
    form.resetFields();
    if (props.record) {
      form.setFieldsValue({
        ...props.record,
      });
    }
  }, [props.record, props.visible, form]);

  return (
    <Modal
      title={props.record ? "编辑内容标签" : "新增内容标签"}
      open={props.visible}
      maskClosable={false}
      onCancel={_handler.onCancel}
      onOk={_handler.onOk}
      width={400}
    >
      <Form form={form} layout={"vertical"}>
        <Form.Item label="标签名称" name="label" required>
          <Input />
        </Form.Item>
        <Form.Item label="标签描述" name="desc">
          <Input.TextArea autoSize={{ minRows: 2, maxRows: 4 }} />
        </Form.Item>
      </Form>
    </Modal>
  );
}
